package com.tan.javatest.synchronize;

/*
 * Copyright (C) 2018 重庆一聊高科技有限公司
 * 版权所有
 *
 * 功能描述：测试Synchronized同步锁
 * 作者：txj
 * 创建时间：2019/2/18
 *
 * 修改人：
 * 修改描述：
 * 修改日期
 */
public class TestSynchronize {

    public static void main(String args[]) {
        final PrintNum printNum = new PrintNum();

        new Thread("thread1") {
            @Override
            public void run() {
                printNum.printNum(Thread.currentThread().getName());
            }
        }.start();
        new Thread("thread2") {
            @Override
            public void run() {
                printNum.printNum(Thread.currentThread().getName());
            }
        }.start();
    }

}


class PrintNum {

    private int num = 0;

    synchronized void printNum(String threadName) {
        if (threadName.equals("thread1")) {
            num += 300;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else if (threadName.equals("thread2")) {
            num -= 100;
        }
        System.out.println(threadName + ": " + num);
    }

}